package com.jxw.cidiansdkdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.jxw.cidian.IJwarService;
import com.jxw.video.IVideoLogin;
import com.jxw.video.VideoActiveCallback;


//视频激活接口封装
public class VideoLoginWrapper {

	private static final String TAG = "VideoLoginWrapper";
	private OnVerify mCallback = null;
	private Context mContext;
	private IVideoLogin mVideoLogin;
	private ServiceConnection mJhtServiceConnection;

	public interface OnVerify {
		/**
		 * 视频激活接口是否成功
		 * @param success true视频激活接口成功
		 *                false 视频激活接口失败
		 */
		void ActiveResult(boolean success);
	}

	public VideoActiveCallback mActiveCallback = new VideoActiveCallback.Stub() {

		@Override
		public void ActiveResult(boolean success) throws RemoteException {
			if(mCallback!=null){
				mCallback.ActiveResult(success);
			}
		}
	};


	public VideoLoginWrapper(Context context) {
		mContext = context;
	}
	
	public void start(OnVerify cb) {
		this.mCallback = cb;
		mJhtServiceConnection = new ServiceConnection() {
		    // Called when the connection with the service is established
		    public void onServiceConnected(ComponentName className, IBinder service) {
		        // Following the example above for an AIDL interface,
		        // this gets an instance of the IRemoteInterface, which we can use to call on the service
		    	synchronized (this) {
					mVideoLogin = IVideoLogin.Stub.asInterface(service);
					try {
						mVideoLogin.registerVideoActiveCallback(mActiveCallback);
					} catch (Exception e) {
						e.printStackTrace();
					}
		    	}

		    }
		    
		    // Called when the connection with the service disconnects unexpectedly
		    public void onServiceDisconnected(ComponentName className) {
		    	synchronized (this) {
					mVideoLogin = null;
		    	}
		    }
		};
		Intent intent = new Intent();
		intent.setClassName("com.jxw.video", "com.jxw.ynas.VideoLoginService");
		if (!mContext.bindService(intent, mJhtServiceConnection, Context.BIND_AUTO_CREATE)) {

		}
	}

	public void activeVideo(){
		if (mVideoLogin != null){
			try {
				mVideoLogin.ActiveVideo();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}


	public void unregisterVideoCallback() {
		if (mVideoLogin != null)
			try {
				mVideoLogin.unregisterVideoCallback(mActiveCallback);

			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public void release() {
		synchronized (this) {
			if (mVideoLogin != null)
				try {
					mVideoLogin.unregisterVideoCallback(mActiveCallback);
				} catch (Exception e) {
					e.printStackTrace();
				}
			if (mVideoLogin != null) {
				try {
					mContext.unbindService(mJhtServiceConnection);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
				mVideoLogin = null;
			}
		}
	}


}